import React, { useState } from 'react';
import { 
  Button, 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions, 
  FormGroup, 
  FormControlLabel, 
  Checkbox, 
  Typography,
  CircularProgress,
  Alert,
  Box
} from '@mui/material';
import DownloadIcon from '@mui/icons-material/Download';
import { exportService } from '../services/exportOrImportService';

/**
 * 数据导出组件
 * 允许用户选择并导出IndexedDB中的数据
 */
const ExportData = ({ open, onClose }) => {
  // 选择要导出的数据类型
  const [selections, setSelections] = useState({
    userData: true,
    contacts: true,
    addressBook: true,
    messages: true
  });
  
  // 导出状态
  const [exporting, setExporting] = useState(false);
  const [exportError, setExportError] = useState(null);
  const [exportSuccess, setExportSuccess] = useState(false);

  // 处理选择变更
  const handleSelectionChange = (event) => {
    setSelections({
      ...selections,
      [event.target.name]: event.target.checked
    });
  };

  // 处理导出操作
  const handleExport = async () => {
    setExporting(true);
    setExportError(null);
    setExportSuccess(false);
    
    try {
      // 根据选择导出不同的数据
      const exportData = {};
      
      if (selections.userData) {
        exportData.userData = await exportService.exportUserData();
      }
      
      if (selections.contacts) {
        exportData.contacts = await exportService.exportContacts();
      }
      
      if (selections.addressBook) {
        exportData.addressBook = await exportService.exportAddressBook();
      }
      
      if (selections.messages) {
        exportData.messages = await exportService.exportMessages();
      }
      
      // 添加导出时间
      exportData.exportDate = new Date().toISOString();
      
      // 下载为JSON文件
      exportService.downloadAsJson(exportData, 'mechat-export.json');
      setExportSuccess(true);
      
      // 3秒后自动关闭对话框
      setTimeout(() => {
        if (exportSuccess) onClose();
      }, 3000);
    } catch (error) {
      console.error('导出数据失败:', error);
      setExportError('导出数据失败: ' + error.message);
    } finally {
      setExporting(false);
    }
  };

  // 重置状态
  const handleClose = () => {
    setExportError(null);
    setExportSuccess(false);
    onClose();
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>导出数据</DialogTitle>
      <DialogContent>
        <Typography variant="body2" color="textSecondary" paragraph>
          选择要导出的数据类型。导出的数据将以JSON格式下载到您的设备上。
        </Typography>
        
        <FormGroup>
          <FormControlLabel
            control={<Checkbox checked={selections.userData} onChange={handleSelectionChange} name="userData" />}
            label="用户信息"
          />
          <FormControlLabel
            control={<Checkbox checked={selections.contacts} onChange={handleSelectionChange} name="contacts" />}
            label="联系人"
          />
          <FormControlLabel
            control={<Checkbox checked={selections.addressBook} onChange={handleSelectionChange} name="addressBook" />}
            label="通讯录"
          />
          <FormControlLabel
            control={<Checkbox checked={selections.messages} onChange={handleSelectionChange} name="messages" />}
            label="聊天记录"
          />
        </FormGroup>
        
        {exportError && (
          <Alert severity="error" sx={{ mt: 2 }}>
            {exportError}
          </Alert>
        )}
        
        {exportSuccess && (
          <Alert severity="success" sx={{ mt: 2 }}>
            数据导出成功！
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} disabled={exporting}>
          取消
        </Button>
        <Button 
          onClick={handleExport} 
          color="primary" 
          disabled={exporting || !Object.values(selections).some(Boolean)}
          startIcon={exporting ? <CircularProgress size={20} /> : <DownloadIcon />}
        >
          {exporting ? '导出中...' : '导出'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

/**
 * 导出按钮组件
 * 用于在界面上显示导出按钮并打开导出对话框
 */
export const ExportButton = () => {
  const [open, setOpen] = useState(false);
  
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  
  return (
    <>
      <Button
        variant="outlined"
        color="primary"
        startIcon={<DownloadIcon />}
        onClick={handleOpen}
        size="small"
      >
        导出数据
      </Button>
      <ExportData open={open} onClose={handleClose} />
    </>
  );
};

export default ExportData;